package cn.fl.institution.controller;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.logger.eum.LogOperEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.institution.condition.PrjInsRedmInterfaceInfoQC;
import cn.fl.institution.constant.PrjInsRedmInterfaceInfoConstant;
import cn.fl.institution.dto.PrjInsRedmInterfaceInfoDTO;
import cn.fl.institution.service.IPrjInsRedmInterfaceInfoService;
import cn.fl.institution.vo.PrjInsRedmInterfaceInfoVO;
import cn.fl.project.dto.PrjPrdPaySchMDTO;
import cn.fl.project.service.IPrjPrdPaySchMApiService;
import cn.fl.ref.fribaseinfo.service.IFriBaseInfoService;
import cn.fl.ref.fribaseinfo.vo.FriBaseInfoVO;
import com.alibaba.fastjson.JSON;
import fl.ref.fribaseinfo.condition.FriBaseInfoQueryCondition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: 资管项目赎回表 控制层
 */
@Controller
@RequestMapping("/institution/prjinsredminterfaceinfo")
public class PrjInsRedmInterfaceInfoController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(PrjInsRedmInterfaceInfoController.class);

    /**
     * PrjInsRedmInfo 服务层BEAN
     */
    @Autowired
    private IPrjInsRedmInterfaceInfoService prjInsRedmInterfaceInfoService;
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;

    @Autowired
    private IFriBaseInfoService friBaseInfoService;

    @Autowired
    private IPrjPrdPaySchMApiService prjPrdPaySchMApiService;


    /**
     * 初始化资方赎回接口信息
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initInsRedmInterfaceInfo.do")
    @ResponseBody
    public Object initInsRedmInterfaceInfo(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.newLogger("加载资方赎回接口列表").setLogOperType(LogOperEnum.REQ).setKeys("initInsRedmInterfaceInfo",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();
        String prjId = request.getParameter("prjId");
        String payerStsCd = request.getParameter("payerStsCd");
        String paySchNo = request.getParameter("paySchNo");
        String paySchId = request.getParameter("paySchId");
        String insCode = request.getParameter("insCode");
        if(StringUtils.isEmpty(prjId)){
            BaseLogUtils.newLogger("加载资方赎回接口列表,项目ID不能为空").setLogOperType(LogOperEnum.REQ).setKeys("initInsRedmInterfaceInfo",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();
            return null;
        }
        if(StringUtils.isEmpty(paySchNo)){
            PrjPrdPaySchMDTO prjPrdPaySchMDTO = prjPrdPaySchMApiService.selectPrjPrdPaySchMById(Long.valueOf(paySchId));
            if(null == prjPrdPaySchMDTO){
                BaseLogUtils.newLogger("加载资方赎回接口列表,支付表主表不能为空").setLogOperType(LogOperEnum.REQ).setKeys("initInsRedmInterfaceInfo",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();
                return null;
            }
            paySchNo = prjPrdPaySchMDTO.getPaySchNo();
        }
        //查询机构ID
        FriBaseInfoQueryCondition friBaseInfoQueryCondition = new FriBaseInfoQueryCondition();
        friBaseInfoQueryCondition.setSysCd(CurrentThreadContext.getCurrentSysCd());
        friBaseInfoQueryCondition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
        friBaseInfoQueryCondition.setInsCode(insCode);
        List<FriBaseInfoVO> friBaseInfoVOS = friBaseInfoService.searchList(friBaseInfoQueryCondition);
        if(CollectionUtils.isEmpty(friBaseInfoVOS)){
            BaseLogUtils.newLogger("加载资方赎回接口列表,融资机构信息不存在").setLogOperType(LogOperEnum.REQ).setKeys("initInsRedmInterfaceInfo","friBaseInfoQueryCondition="+ JSON.toJSONString(friBaseInfoQueryCondition),this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();
            return null;
        }
        PrjInsRedmInterfaceInfoQC qc = new PrjInsRedmInterfaceInfoQC();
        qc.setPrjId(Long.valueOf(prjId));
        if(StringUtils.isNotEmpty(paySchNo)){
            qc.setPaySchNo(paySchNo);
        }
        if(StringUtils.isNotEmpty(paySchId)){
            qc.setPaySchId(Long.valueOf(paySchId));
        }
        if(StringUtils.isNotEmpty(insCode)){
            qc.setInsCode(insCode);
        }
        qc.setOperationType(PrjInsRedmInterfaceInfoConstant.INS_REDM_INTERFACE_OPERATION_TYPE_0);
        /**
         * 先查询是否有试算数据
         */
        List<PrjInsRedmInterfaceInfoVO> list = new ArrayList<>();
        list = prjInsRedmInterfaceInfoService.selectInsRedmInterfaceInfoList(qc);
        if(CollectionUtils.isEmpty(list)){
            PrjInsRedmInterfaceInfoVO prjInsRedmInterfaceInfoVO = new PrjInsRedmInterfaceInfoVO();
            prjInsRedmInterfaceInfoVO.setPrjId(Long.valueOf(prjId));
            prjInsRedmInterfaceInfoVO.setOperationType("0");
            prjInsRedmInterfaceInfoVO.setPayerStsCd(payerStsCd);
            prjInsRedmInterfaceInfoVO.setPaySchNo(paySchNo);
            prjInsRedmInterfaceInfoVO.setPaySchId(Long.valueOf(paySchId));
            prjInsRedmInterfaceInfoVO.setInsCode(insCode);
            prjInsRedmInterfaceInfoVO.setFundRasInsId(friBaseInfoVOS.get(0).getId());
            list.add(prjInsRedmInterfaceInfoVO);
        }
        ListPageVO<PrjInsRedmInterfaceInfoVO> listPage = new ListPageVO<PrjInsRedmInterfaceInfoVO>(list, list.size());
        BaseLogUtils.newLogger("加载资方赎回接口列表结束").setLogOperType(LogOperEnum.REQ).setKeys("initInsRedmInterfaceInfo","list="+ JSON.toJSONString(list),CurrentThreadContext.getCurrentUserName()).info();
        return listPage;
    }

    /**
     * 初始化资方赎回接口信息列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initInsRedmInterfaceInfoList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initInsRedmInterfaceInfoList(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.newLogger("加载资方赎回接口列表").setLogOperType(LogOperEnum.REQ).setKeys("initInsRedmInterfaceInfoList",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();
        String prjId = request.getParameter("prjId");
        String paySchId = request.getParameter("paySchId");
        String operationType = request.getParameter("operationType");
        String payerStsCd = request.getParameter("payerStsCd");
        PrjInsRedmInterfaceInfoQC qc = new PrjInsRedmInterfaceInfoQC();
        if(StringUtils.isEmpty(prjId)){
            BaseLogUtils.newLogger("加载资方赎回接口列表,项目ID不能为空").setLogOperType(LogOperEnum.REQ).setKeys("initInsRedmInterfaceInfoList",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();
            return null;
        }
        if(StringUtils.isNotEmpty(paySchId)){
            qc.setPaySchId(Long.valueOf(paySchId));
        }
        if(StringUtils.isNotEmpty(operationType)){
            qc.setOperationType(operationType);
        }
        qc.setPrjId(Long.valueOf(prjId));
        List<PrjInsRedmInterfaceInfoVO> list = this.prjInsRedmInterfaceInfoService.selectInsRedmInterfaceInfoList(qc);
        for(PrjInsRedmInterfaceInfoVO prjInsRedmInterfaceInfoVO : list){
            prjInsRedmInterfaceInfoVO.setPayerStsCd(payerStsCd);
        }
        ListPageVO<PrjInsRedmInterfaceInfoVO> listPage = new ListPageVO<PrjInsRedmInterfaceInfoVO>(list, list.size());
        return listPage;
    }

    /**
     * 调用试算接口
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/calculateInsRedmInterfaceInfo.do")
    @ResponseBody
    public Object calculateInsRedmInterfaceInfo(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.newLogger("试算资方赎回接口数据").setLogOperType(LogOperEnum.REQ).setKeys("calculateInsRedmInterfaceInfo",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();
        DataResultDTO resultDTO = new DataResultDTO(BaseConstant.IS_YESNO_YES, "试算成功!");
        String prjId = request.getParameter("prjId");
        String paySchId = request.getParameter("paySchId");
        String fundRasInsId = request.getParameter("fundRasInsId");
        String insCode = request.getParameter("insCode");
        if(StringUtils.isEmpty(prjId)){
            BaseLogUtils.newLogger("试算资方赎回接口数据,项目ID不能为空").setLogOperType(LogOperEnum.REQ).setKeys("calculateInsRedmInterfaceInfo",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();
            resultDTO.setSuccess(BaseConstant.IS_YESNO_NO);
            resultDTO.setInfo("试算资方赎回接口数据,项目ID不能为空");
            return resultDTO;
        }
        if(StringUtils.isEmpty(paySchId)){
            BaseLogUtils.newLogger("试算资方赎回接口数据,支付表ID不能为空").setLogOperType(LogOperEnum.REQ).setKeys("calculateInsRedmInterfaceInfo",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();
            resultDTO.setSuccess(BaseConstant.IS_YESNO_NO);
            resultDTO.setInfo("试算资方赎回接口数据,支付表ID不能为空");
            return resultDTO;
        }
        if(StringUtils.isEmpty(insCode)){
            BaseLogUtils.newLogger("试算资方赎回接口数据,机构CODE不能为空").setLogOperType(LogOperEnum.REQ).setKeys("calculateInsRedmInterfaceInfo",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();
            resultDTO.setSuccess(BaseConstant.IS_YESNO_NO);
            resultDTO.setInfo("试算资方赎回接口数据,机构CODE不能为空");
            return resultDTO;
        }
        if(StringUtils.isEmpty(fundRasInsId)){
            BaseLogUtils.newLogger("试算资方赎回接口数据,机构ID不能为空").setLogOperType(LogOperEnum.REQ).setKeys("calculateInsRedmInterfaceInfo",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();
            resultDTO.setSuccess(BaseConstant.IS_YESNO_NO);
            resultDTO.setInfo("试算资方赎回接口数据,机构ID不能为空");
            return resultDTO;
        }
        //调用SKD004 进行测算
        PrjInsRedmInterfaceInfoQC prjInsRedmInterfaceInfoQC = new PrjInsRedmInterfaceInfoQC();
        prjInsRedmInterfaceInfoQC.setPrjId(Long.valueOf(prjId));
        prjInsRedmInterfaceInfoQC.setPaySchId(Long.valueOf(paySchId));
        prjInsRedmInterfaceInfoQC.setFundRasInsId(StringUtils.isNotBlank(fundRasInsId)?Long.valueOf(fundRasInsId):null);
        prjInsRedmInterfaceInfoQC.setInsCode(insCode);
        BaseLogUtils.newLogger("开始调用试算接口").setLogOperType(LogOperEnum.REQ).setKeys("calculateInsRedmInterfaceInfo","prjInsRedmInterfaceInfoQC="+ JSON.toJSONString(prjInsRedmInterfaceInfoQC),CurrentThreadContext.getCurrentUserName()).info();
        resultDTO = this.prjInsRedmInterfaceInfoService.calculation(prjInsRedmInterfaceInfoQC);
        BaseLogUtils.newLogger("调用试算接口结束").setLogOperType(LogOperEnum.REQ).setKeys("calculateInsRedmInterfaceInfo","resultDTO="+ JSON.toJSONString(resultDTO),CurrentThreadContext.getCurrentUserName()).info();
        if(BaseConstant.IS_YESNO_YES == resultDTO.getSuccess()){
            //已结清直接返回
            if(PrjInsRedmInterfaceInfoConstant.SETTLED_TRIAL_FAILED.equals(resultDTO.getCode())){
                resultDTO.setInfo("该笔订单已结清,请直接发起赎回流程");
                return resultDTO;
            }
            PrjInsRedmInterfaceInfoDTO prjInsRedmInterfaceInfoDTO = (PrjInsRedmInterfaceInfoDTO)resultDTO.getData();
            PrjInsRedmInterfaceInfoVO prjInsRedmInterfaceInfoVO = new PrjInsRedmInterfaceInfoVO();
            prjInsRedmInterfaceInfoVO.setPrjId(Long.valueOf(prjId));
            prjInsRedmInterfaceInfoVO.setPaySchId(Long.valueOf(paySchId));
            prjInsRedmInterfaceInfoVO.setFundRasInsId(Long.valueOf(fundRasInsId));
            prjInsRedmInterfaceInfoVO.setRedmAmt(DecimalUtils.convertFenToYuan(prjInsRedmInterfaceInfoDTO.getRedmAmt()));
            prjInsRedmInterfaceInfoVO.setPrincipalAmt(DecimalUtils.convertFenToYuan(prjInsRedmInterfaceInfoDTO.getPrincipalAmt()));
            prjInsRedmInterfaceInfoVO.setInterestAmt(DecimalUtils.convertFenToYuan(prjInsRedmInterfaceInfoDTO.getInterestAmt()));
            prjInsRedmInterfaceInfoVO.setPenaltyAmt(DecimalUtils.convertFenToYuan(prjInsRedmInterfaceInfoDTO.getPenaltyAmt()));
            prjInsRedmInterfaceInfoVO.setCrtTm(new Date());
            resultDTO.setData(prjInsRedmInterfaceInfoVO);
            resultDTO.setInfo("试算成功");
            BaseLogUtils.newLogger("调用试算接口结束,拼装试算结果结束").setLogOperType(LogOperEnum.REQ).setKeys("calculateInsRedmInterfaceInfo","resultDTO="+ JSON.toJSONString(resultDTO),"prjInsRedmInterfaceInfoVO="+ JSON.toJSONString(prjInsRedmInterfaceInfoVO),CurrentThreadContext.getCurrentUserName()).info();
        }else{
            resultDTO.setSuccess(BaseConstant.IS_YESNO_NO);
            if(StringUtils.isBlank(resultDTO.getInfo())){
                resultDTO.setInfo("调用资方赎回接口测算失败,请稍后重试");
            }
        }
        return resultDTO;
    }




}

